using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Portal.Extensions;
using Portal.Models;
using ST.Application.UserServices;
using ST.Domain.Entities;

namespace Portal.Controllers
{
    public class LoginController : Controller
    {
        private readonly IUserService _userService;

        public LoginController(IUserService userService)
        {
            _userService = userService;
        }
        
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var user = _userService.CheckUser(model.UserName, model.Password);
                if (user != null)
                {
                    //记录Session
                    HttpContext.Session.SetString("CurrentUserId", user.Id.ToString());
                    HttpContext.Session.Set<User>("CurrentUser", user);
                    //跳转到系统首页
                    return RedirectToAction("Index", "Menu");
                }
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            return View();
        }
    }
}